package top.mcwebsite.playandroid.common.basic.impl.settings

import android.content.Context
import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import top.mcwebsite.playandroid.common.api.AppService
import top.mcwebsite.playandroid.lib.common.ext.isNightModeActiveEx
import top.mcwebsite.playandroid.lib.servicemanager.core.ServiceManager

object AppSettings {


    private val Context.appSettings: DataStore<Preferences> by preferencesDataStore(name = "AppSettings")

    private const val TAG = "AppSettings"

    private val DARK_MODE = booleanPreferencesKey("dark_mode")
    private val FOLLOW_SYSTEM_THEME = booleanPreferencesKey("follow_system_theme")

    private val isDarkModeStateFlow = MutableStateFlow<Boolean?>(null)
    private val isFollowSystemThemeStateFlow = MutableStateFlow<Boolean?>(null)

    private val scope: CoroutineScope = MainScope()

    fun init(isSync: Boolean = false) {
        Log.d(TAG, "init isSync =  $isSync")
        if (!isSync) {
            runBlocking {
                getAppSettingsDataStore().data.first().init()
            }
        } else {
            scope.launch {
                getAppSettingsDataStore().data.first().init()
            }
        }
    }

    private fun Preferences.init() {
        scope.launch {
            isFollowSystemThemeStateFlow.emit(this@init[FOLLOW_SYSTEM_THEME] ?: true)
            val isDarkMode = if (isFollowSystemThemeStateFlow.value == true) {
                val systemDarkMode =
                    ServiceManager.getService<AppService>().getApplication().resources.configuration.isNightModeActiveEx()
                val isDarkModeInPrefs = this@init[DARK_MODE]
                if (isDarkModeInPrefs != null && systemDarkMode != isDarkModeInPrefs) {
                    setDarkMode(systemDarkMode)
                }
                systemDarkMode
            } else {
                this@init[DARK_MODE] ?: false
            }
            isDarkModeStateFlow.emit(isDarkMode)
        }
    }

    private fun getAppSettingsDataStore(): DataStore<Preferences> =
        ServiceManager.getService<AppService>().getApplication().appSettings

    fun isDarkMode(): Boolean {
        return isDarkModeStateFlow.value ?: kotlin.run {
            runBlocking {
                init()
                isDarkModeStateFlow.value ?: false
            }
        }
    }

    fun setDarkMode(isDarkMode: Boolean) {
        scope.launch {
            getAppSettingsDataStore().edit {
                it[DARK_MODE] = isDarkMode
            }
            this@AppSettings.isDarkModeStateFlow.emit(isDarkMode)
        }
    }


    fun isFollowSystemTheme(): Boolean {
        return isFollowSystemThemeStateFlow.value ?: kotlin.run {
            init()
            isFollowSystemThemeStateFlow.value ?: true
        }
    }

    fun setFollowSystemTheme(isFollow: Boolean) {
        scope.launch {
            getAppSettingsDataStore().edit {
                it[FOLLOW_SYSTEM_THEME] = isFollow
            }
            this@AppSettings.isFollowSystemThemeStateFlow.emit(isFollow)
        }
    }

    fun isDarkModeFlow() = isDarkModeStateFlow.asStateFlow()

    fun isFollowSystemThemeFlow() = isFollowSystemThemeStateFlow.asStateFlow()
}